package com.example.a3axismotion;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import com.example.a3axismotion.utlis.BoardDefaults;
import com.example.a3axismotion.view.Rectangle;
import com.google.android.things.pio.Gpio;
import com.google.android.things.pio.PeripheralManager;
import com.google.android.things.pio.Pwm;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Skeleton of an Android Things activity.
 * <p>
 * Android Things peripheral APIs are accessible through the class
 * PeripheralManagerService. For example, the snippet below will open a GPIO pin and
 * set it to HIGH:
 *
 * <pre>{@code
 * PeripheralManagerService service = new PeripheralManagerService();
 * mLedGpio = service.openGpio("BCM6");
 * mLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
 * mLedGpio.setValue(true);
 * }</pre>
 * <p>
 * For more complex peripherals, look for an existing user-space driver, or implement one if none
 * is available.
 *
 * @see <a href="https://github.com/androidthings/contrib-drivers#readme">https://github.com/androidthings/contrib-drivers#readme</a>
 */
public class MainActivity extends Activity implements View.OnTouchListener, View.OnClickListener {
    Button mBtTop;
    Button btLeft;
    Button btRight;
    Button btDown;
    Button btClear;
    Button bt_save;
    Rectangle lattice;
    /**
     * 长按超过0.3秒，触发长按事件
     */
    private static final int LONG_PRESSTIME = 300;

    /**
     * 计时器，计时点击时长
     */
    Timer timer;
    TimerTask timerTask;
    int x = 0;
    //   发送消息与终止方法：先定义一个ScheduledExecutorService对象，然后调用scheduleWithFixedDelay()方法

    private ScheduledExecutorService scheduledExecutor;
    ExecutorService singleThreadExecutor2;
    /**
     * 判断是否进行点击
     */
    boolean isClick = true;
    boolean isFirstSend = false;
    public boolean isOnLongClick = false;

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String DEVICE_RPI3 = "BCM7";
    // Parameters of the servo PWM
    private static final double MIN_ACTIVE_PULSE_DURATION_MS = 1;
    private static final double PULSE_PERIOD_MS = 0.450;  // Frequency of 50Hz (1000/20)
    // Parameters for the servo movement over time
    private static final int INTERVAL_BETWEEN_STEPS_MS = 1;
    int xCount = 0;
    int yCount = 0;
    private Gpio mGpio;
    private Handler mHandler = new Handler();
    private Pwm mPwm;

    private double mActivePulseDuration;
    private PeripheralManager peripheralManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initIot();
        initView();
    }

    private void initIot() {
        Log.i(TAG, "Starting PwmActivity");

        peripheralManager = PeripheralManager.getInstance();
        try {
            mGpio = peripheralManager.openGpio(DEVICE_RPI3);
            //设置引脚为输出信号
            mGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_HIGH);
        } catch (IOException e) {
            Log.d(TAG, "Start 2222 PWM pulse");
            e.printStackTrace();
        }
        try {
            String pinName = BoardDefaults.getPWMPort();
            mActivePulseDuration = MIN_ACTIVE_PULSE_DURATION_MS;
            mPwm = PeripheralManager.getInstance().openPwm(pinName);
            // Always set frequency and initial duty cycle before enabling PWM
            mPwm.setPwmFrequencyHz(1);
            mPwm.setPwmDutyCycle(40);
            mPwm.setEnabled(false);
            // Post a Runnable that continuously change PWM pulse width, effectively changing the
            // servo position
            Log.d(TAG, "Start changing PWM pulse");
            mHandler.post(mChangePWMRunnable);
        } catch (IOException e) {
            Log.e(TAG, "Error on PeripheralIO API", e);
        }
    }


    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        mBtTop = findViewById(R.id.bt_top);
        btLeft = findViewById(R.id.bt_left);
        btRight = findViewById(R.id.bt_right);
        btDown = findViewById(R.id.bt_down);
        lattice = findViewById(R.id.lattice);
        btClear = findViewById(R.id.bt_clear);
        bt_save = findViewById(R.id.bt_save);


        mBtTop.setOnTouchListener(this);
        btLeft.setOnTouchListener(this);
        btRight.setOnTouchListener(this);
        btDown.setOnTouchListener(this);
        bt_save.setOnClickListener(this);
        btClear.setOnClickListener(this);


    }


    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(final View v, MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN && event.getPointerCount() == 1) {
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    isOnLongClick = true;
                    //长按逻辑触发，isClick置为false，手指移开后，不触发点击事件
                    isClick = false;
                    //手指按下时触发不停的发送消息
//                    updateAddOrSubtract(v.getId());


                }
            };
            isClick = true;
            timer.schedule(timerTask, LONG_PRESSTIME, 1000 * 60 * 60 * 24);
        } else if (event.getAction() == MotionEvent.ACTION_UP && event.getPointerCount() == 1) {
            //手指抬起时停止发送
            stopAddOrSubtract();
            if (isClick) {
                isOnLongClick = true;
//                try {
//                    mPwm.setEnabled(true);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }

                mHandler.post(mChangePWMRunnable);
            }

//            try {
//                mPwm.setEnabled(false);
//            } catch (IOException e) {
//                e.printStackTrace();
//
//            }
            Log.d(TAG, "xCount:" + xCount);
            //取消计时
            timerTask.cancel();
            timer.cancel();

        }
        return true;
    }


    private void updateAddOrSubtract(int viewId) {
        try {
            mPwm.setEnabled(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        final int vid = viewId;
        scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutor.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                xCount = xCount + 1;
                yCount += yCount;
                Log.d(TAG, "sssss");
                Log.d(TAG, "xCount:" + xCount);
                Log.d(TAG, "yCount:" + yCount);

                Message msg = new Message();
                msg.what = vid;
                myHandler.sendMessage(msg);
            }
        }, 0, 1, TimeUnit.MILLISECONDS);    //每间隔100ms发送Message
    }

    private void stopAddOrSubtract() {
        if (scheduledExecutor != null) {
            scheduledExecutor.shutdownNow();
            scheduledExecutor = null;
        }
    }


    @SuppressLint("HandlerLeak")
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case R.id.bt_top:
//                    sendData();

                    lattice.xChange2Y(false);
                    break;
                case R.id.bt_down:
//                    sendData();

                    lattice.xChange2Y(true);

                    break;
                case R.id.bt_left:
//                    sendData();

                    lattice.xChange2X(false);

                    break;
                case R.id.bt_right:
//                    sendData();

                    lattice.xChange2X(true);
                    break;

                default:
                    break;
            }
        }
    };


    private Runnable mChangePWMRunnable = new Runnable() {

        @Override
        public void run() {

            try {
                mPwm.setEnabled(true);
            } catch (IOException e) {
                e.printStackTrace();

            }

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                mPwm.setEnabled(false);
            } catch (IOException e) {
                e.printStackTrace();

            }

//            mHandler.post(mChangePWMRunnable);
        }
    };

    @Override
    protected void onDestroy() {
        Log.d("AAAAAAAAAAAAa", "close");
        super.onDestroy();
        // Remove pending Runnable from the handler.
        myHandler.removeCallbacks(mChangePWMRunnable);
        Log.d("AAAAAAAAAAAAa", "close");
        try {

            mPwm.setEnabled(false);
            mPwm.close();
            Log.d("AAAAAAAAAAAAa", "close1");
        } catch (IOException e) {
            Log.d("AAAAAAAAAAAAa", "close2");
            Log.d(TAG, e.getMessage());
        } finally {
            Log.d("AAAAAAAAAAAAa", "close3");
            mPwm = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_commit:
                break;
            case R.id.bt_automatic:
                break;
            case R.id.bt_save:
                break;
            case R.id.bt_clear:
                xCount = 0;
                yCount = 0;
                Log.d(TAG, "xCount:" + xCount);
                Log.d(TAG, "yCount:" + yCount);
                break;
            // TODO: 2018/11/4  handler 还没写接收的东西
            default:
                break;
        }
    }


}
